#include "MapZoom.h"

Map::Map(): QMainWindow(0){
    map = new LightMaps(this);
    setCentralWidget(map);
    map->setFocus();

    grabZoomKeys(true);

    location = new LocationInfo();
    connect(location, SIGNAL(positionChanged(qreal, qreal)), this, SLOT(newCenter(qreal, qreal)));

    connect(map, SIGNAL(updateTrackButton()), this, SLOT(updateButton()));

    QAction *osloAction = new QAction("&Oslo", this);
    QAction *osmAction = new QAction("About OpenStreetMap", this);
    trackAction = new QAction("GPS tracker off", this);
    trackAction->setChecked(false);
    trackAction->setCheckable(true);
    waypointAction = new QAction("Set a waypoint", this);
    waypointAction->setChecked(false);
    waypointAction->setCheckable(true);
    connect(trackAction, SIGNAL(triggered()), map, SLOT(toggleTrackMap()));
    connect(osloAction, SIGNAL(triggered()), SLOT(chooseOslo()));
    connect(osmAction, SIGNAL(triggered()), SLOT(aboutOsm()));
    connect(waypointAction, SIGNAL(triggered()), map, SLOT(waypointSlot()));

    QMenu *menu = menuBar()->addMenu("&Options");
    menu->addAction(osloAction);
    menu->addAction(osmAction);
    menu->addAction(trackAction);
    menu->addAction(waypointAction);
}

void Map::grabZoomKeys(bool grab){
    if (!winId()) {
       qWarning("Can't grab keys unless we have a window id");
       return;
    }

    unsigned long val = (grab) ? 1 : 0;
    Atom atom = XInternAtom(QX11Info::display(), "_HILDON_ZOOM_KEY_ATOM", False);
    if (!atom) {
        qWarning("Unable to obtain _HILDON_ZOOM_KEY_ATOM. This example will only work "
                 "on a Maemo 5 device!");
        return;
    }

    XChangeProperty (QX11Info::display(), winId(), atom, XA_INTEGER, 32,
                     PropModeReplace, reinterpret_cast<unsigned char *>(&val), 1);
}

void Map::updateButton(){
    trackAction->setChecked(true);
}

void Map::newCenter(qreal lat, qreal lng) {
    if (map->getTrackMap()){
        map->setCenter(lng, lat);
    }
}

void Map::chooseOslo() {
    map->setCenter(59.9138204, 10.7387413);
}

void Map::aboutOsm() {
    QDesktopServices::openUrl(QUrl("http://www.openstreetmap.org"));
}
